//vuex状态管理
const store = new Vuex.Store({
    state: {
        selectedEmployees: []
    },
    mutations: {
        updateEmployees:function(state,param) {
            //判断员工是否已选
            for(var i=0;i<state.selectedEmployees.length;i++){
                if(state.selectedEmployees[i].id == param.id){
                    state.selectedEmployees.splice(i,1) //如果有相同员工id，则删除该员工
                    return false
                }
            }
            state.selectedEmployees.push(param);
        },
        deleteEmployee:function(state,param){
            //clearAll为true时选择员工置空
            if(!!param.clearAll){
                state.selectedEmployees = [];
                return false;
            }
            //删除选中员工
            for(var i=0;i<state.selectedEmployees.length;i++){
                if(state.selectedEmployees[i].id == param.id){
                    state.selectedEmployees.splice(i,1)
                    break
                }
            }
            return false;
        }
    }
})

//vue实例
var customerApp = new Vue({
    el:'#main',
    data:{
        /*渲染数据*/
        sLoading: true, //LOADING
        custType: 0, //记录类型 0 意向 1 签约 2 潜在
        userInfo: {}, //当前登陆用户名信息
        currentTime: -1, //当前时间辍
        formData: {
            records: [],
        },//渲染数据
        pageSizeSelected: -1,//每页选择条数
        filterParameters: {
            searchKey: '', //搜索关键字
            provinceCode: -1, //省编码
            cityCode: -1, //市编码
            countyCode: -1, //区编码
            startDate: '', //搜索开始的日期(格式:2017-8-12)
            endDate: '', //搜索开始的日期(格式:2017-8-12)
            current: 1, //当前页码默认为0
            pageSize: 10, //每页查询条数默认10条
            intentionStatus: 1 //分页只显示签约
        },
        /*模态框显示隐藏*/
        modal: {
            assign: false, //指派
            followRecord: false, //添加跟进记录
            certificate: false, //添加证照
            employee: false, //选择员工
            abutment: false, //对接人
            contact: false, //添加联系人
            intention: false, //添加到意向客户
        },
        //客户暂存区
        custItemStorage:{},
        //跟进记录
        followInfo:{
            id: -1, //添加无 更新有
            custId: -1, //客户id
            customerName: '', //客户名称
            customerType: 0, //客户类型 0 企业
            custConcats: [], //对接人id集合
            followIds: [], //跟进人集合
            followDetail: '', //跟进详情
            followReasonId: -1, //跟进事由id 来源数据词典
            followType:-1, //跟进类型id 来源数据词典
            followTime: -1, //跟进时间
            types: 1, //跟进记录类型 0 意向 1 签约 2 潜在
            //front add
            selectedContactNames: '', //选中的联系人
            selectedContactInfo: [], //选中联系人信息
            allContacts: [], //当前客户的联系人信息
        },
        followRecord:{
            records: [],
        },
        followPage:{
            pageSizeSelected_follow: -1,//每页选择条数
            filterParameters: {
                id: -1, //客户id
                types: 1, //跟进记录类型 0 意向 1 签约 2 潜在
                current: 1, //当前页码默认为0
                pageSize: 10, //每页查询条数默认10条
            }
        },
        /*（选择员工）部门树形数据*/
        departTree: {
            originalData:{}, //获取原始数据
            msg:[],  //存储数据结构改变后的数据
            show: true, //显示隐藏
        },
        departTreeSearchKey: '', //搜索内容
        employeeResult: [], //员工搜索结果
        finalSelectedEmployees: [], //最终显示的员工数据
        //客户处理（详情+编辑）
        handle: {
            display: false, //显示隐藏
            state: 0, // 0 详情  1 编辑
            data: {
                //客户
                basicContent:{
                    id: -1, //客户id
                    customerType: 0, //客户类型(0:企业客户，1：个体客户，2：其他组织)
                    enterpriseNatureCodeId: -1, //公司类型
                    enterpriseStatusCodeId: -1, //经营状况
                    //front add
                    industrySearchContent: '', //所属行业搜索
                }
            },
            //所属行业搜索结果
            industrySearchResult: {
                display: false,
                hasResult: false, //是否查到结果
                content: []
            }
        },
        //获取当前客户的联系人
        contactsData:[],
        //获取当前客户的发票抬头
        invoicesData:[],
        //数据词典
        dictData:{
            contactsType: [], //联系人类型
            licenseType: [], //证照类型
            followupWay: [], //跟进方式
            followupReason: [], //跟进事由
            entrepreneurial: [], //公司类型
            enterpriseAppearance: [], //经营状况
        },
        //请求
        req: {
            //添加联系人
            addContact: {
                contactType: '', //联系人类型
                contactName: '', //姓名
                gender: 0, //性别
                phoneNumber: '', //联系电话
                email: '', //电子邮箱
                wechat: '', //微信
                qq: '', //QQ
                birthday: '', //生日
                gongLiFlag: 0, //公农历
                position: '', //职位
                remark: '', //备注
                types: 1, //0：意向，1:签约 2 潜在
            },
            //添加证照
            addCerticate:{
                custId: -1, //客户id
                docType: -1, //证照类型 来源数据词典 编码
                jpgUrl: '', //JPG图片路径
                pdfUrl: '', //PDF图片路径
            }
        },
        //联系人(客户对接人)
        queryContacts:{
            display: false,
            result: []
        },
        //证书证照记录
        certificateRecord: {
            records: []
        },
        //意向记录
        intentionRecord:{
            records: []
        },
        intentionPage:{
            pageSizeSelected_intention: -1,//每页选择条数
            filterParameters: {
                id: -1, //客户id
                types: 1, //跟进记录类型 0 意向 1 签约 2 潜在
                current: 1, //当前页码默认为0
                pageSize: 10, //每页查询条数默认10条
            }
        },
        //商标案件记录
        caseRecord:{
            records: []
        },
        casePage:{
            pageSizeSelected_case: -1,//每页选择条数
            filterParameters: {
                custId: -1, //客户id
                //types: 1, //跟进记录类型 0 意向 1 签约 2 潜在
                current: 1, //当前页码默认为0
                pageSize: 10, //每页查询条数默认10条
            }
        },
        //in case fast click
        fastClick:{
            //添加证照
            certificate: false,
        }
    },
    store:store,
    components:{
        /*（选择员工）部门树形组件*/
        tree: {
            name: 'tc',
            template: '<section class="visible transition">\
    <section class="title" @click="loadEmployees(msg.id,msg.children)">\
    <i class="dropdown icon"></i>\
    <a>{{msg.name}}</a>\
</section>\
<section class="content">\
    <div v-for="e in employeesData" class="transition employeeItem" :data-id="e.id" @click="selectEmployeeData(e.id,e.employeeName)">{{e.employeeName}}\
    <div class="mask-prevent"></div>\
    <div class="ui checkbox fr">\
    <input type="checkbox" v-model="selectedEmployees" :value="e.id">\
    <label></label>\
    </div>\
    </div>\
    <tc v-for="v in msg.children" :msg="v"></tc>\
</section>\
</section>',
            props: ['msg'],
            components: {

            },
            data:function(){
                return {
                    employeesData: [] //员工数据
                }
            },
            computed:{
                selectedEmployees:function(){
                    var result = [];
                    this.$store.state.selectedEmployees.forEach(function(obj){
                        result.push(obj.id)
                    })
                    return result
                }
            },
            methods:{
                //按部门id加载员工表
                loadEmployees:function(id,arr){
                    var self = this;
                    if(self.employeesData.length == 0 ){
                        Customer.axiosRequest(Customer.interface.queryEmployeeJson,{
                            departmentId: id
                        },function(result){
                            if(result.code == 0){
                                self.employeesData = result.data;
                            }
                        },{
                            type:'post',
                        })
                    }else{
                        return false
                    }
                },
                //选择员工
                selectEmployeeData:function(id,name){
                    //业务限制人数
                    var selectedNum = customerApp.$store.state.selectedEmployees.length;
                    if(!!customerApp.limitedNum(selectedNum,id)){
                        var transParam = {
                            id: id,
                            name: name
                        }
                        store.commit('updateEmployees',transParam)
                    }
                }
            }
        }
    },
    filters:{
        //（选择员工）确认或取消后的显示过滤
        showName:function(arr){
            if(arr.length == 0) return ''
            var result = '';
            for(var i=0;i<arr.length;i++){
                result += arr[i].name;
                result = i == arr.length-1 ? result : result + '、';
            }
            return result
        },
        //转时间辍为（格式2018-01-01）
        dateFormat:function(time,mode){
            /*Arg Guide
             @ time 时间辍
             */
            if (time == null) {
                return '';
            }
            var date = new Date(time);
            var year = date.getFullYear();
            var month = date.getMonth() + 1 >9 ? date.getMonth() + 1 : '0'+ (date.getMonth() + 1);
            var date = date.getDate() >9 ? date.getDate() : '0' + date.getDate();
            if(mode == 'm1'){
                //返回当前月第一天
                var date = '01';
            }
            return year + '-' + month + '-' + date
        },
        //限制字段长度
        limitlength:function(value,num){
            /*Arg Guide
             @ value 字符串
             @ num 限制字段长度
             */
            if(typeof value != 'string' || typeof num != 'number'){
                return;
            }
            return value.slice(0,num)
        },
        //分转万元
        changeMoneyUnit:function(money){
            /*Arg Guide
             @ money 金额(分)
             @ return 金额(万元)
             */
            var money = parseInt(money);
            var unit = 6;
            return (money / Math.pow(10, unit)).toFixed(2);//保留两位有效数字
        }
    },
    /*数据渲染完毕调用*/
    mounted:function(){
        var self = this;
        this.init();
        this.$nextTick(function(){
            //时间控件
            wzERP.Common.singleDate('.single-date');
            //tab切换
            var $menu = $('.tabular.menu');
            $menu.find('.item').tab();
            //ui功能开启
            $('.ui.checkbox').checkbox();
            //联系人类型
            var contactTypeUrl = Customer.interface.dictList + '?code=' + Customer.dictCode[0];
            Customer.axiosRequest(contactTypeUrl,{},function(result){
                if(result.code == 0){
                    self.dictData.contactsType = result.data;
                }
            })
            //remove loading
            setTimeout(function(){
                self.sLoading = false;
            },100)
        })
    },
    watch:{
        //监听页数变化
        pageSizeSelected:function(val){
            this.filterParameters.pageSize = parseInt(val);
            this.filterParameters.current = 1;
            this.renderMain(Customer.interface.queryPage,this.filterParameters);
        },
        //监听跟进记录页数变化
        'followPage.pageSizeSelected_follow':function(val){
            this.followPage.filterParameters.pageSize = parseInt(val);
            this.followPage.filterParameters.current = 1;
            this.renderFollowRecords(Customer.interface.followRecords,this.followPage.filterParameters)
        },
        //监听意向记录页数变化
        'intentionPage.pageSizeSelected_intention':function(val){
            this.intentionPage.filterParameters.pageSize = parseInt(val);
            this.intentionPage.filterParameters.current = 1;
            this.renderIntentionRecords(Customer.interface.intentionRecords,this.intentionPage.filterParameters)
        },
        //监听商标案件记录页数变化
        'casePage.pageSizeSelected_case':function(val){
            this.casePage.filterParameters.pageSize = parseInt(val);
            this.casePage.filterParameters.current = 1;
            this.renderCaseRecords(Customer.interface.caseRecords,this.casePage.filterParameters)
        },
        //（选择员工）监听员工框搜索内容
        departTreeSearchKey:function(val){
            var self = this;
            if(val == ''){
                self.departTree.show = true
            }else{
                self.departTree.show = false
                Customer.axiosRequest(Customer.interface.queryEmployeePage,{
                    searchKey: val
                },function(result){
                    self.employeeResult = result.data;
                },{
                    type: 'post'
                })
            }
        },
        //打开编辑详情页面默认tab第一个
        'handle.display':function(){
            this.$nextTick(function(){
                var $menu = $('.tabular.menu');
                $menu.find('.item').tab();
                $menu.find('.item').eq(0).click();
            })
        }
    },
    computed:{
        //（选择员工）导出选择的员工
        selectedEmployees:function(){
            var result = [];
            this.$store.state.selectedEmployees.forEach(function(obj){
                result.push(obj.id)
            })
            return result
        },
        //获取当前时间辍
        currentTime:function(){
            return new Date().getTime();
        },
    },
    methods:{
        init:function(){
            var self = this;
            var url = Customer.interface.queryPage;
            this.renderMain(url,self.filterParameters);
            //（选择员工）加载树形结构
            this.renderDepartData();
            //获取当前用户信息
            self.gainCurrentUserInfo();
            //添加联系人功能初始化
            Customer.contactFunction({
                types: 1 //0：意向，1:签约 2 潜在
            },'#addContactbox', true);
            //发票抬头功能初始化

            this.$nextTick(function(){
                Customer.invoiceFunction('#addInvoicebox', true);
            })
            //(查看编辑)
            $('.zoom-label').off('click').click(function () {var _this = $(this)[0];Customer.openBigPic('#bigPicShowLayer',_this);});
            Customer.uploadFile('#whole_ibox','#upload_logo_label','#upload_logo_form',0);//企业logo
            Customer.uploadFile('#ml_certificate','#uploadCertificate1_label','#uploadCertificate1_form',1);//上传证照
            //上传pdf功能
            Customer.uploadFilePdf('#addInvoicebox','#uploadProof_label', '#uploadProof_form');//一般纳税人证明
        },
        //渲染客户数据
        renderMain:function(url,param){
            var self = this;
            param = param == undefined ? {} : param;
            Customer.axiosRequest(url,param,function(result){
                self.formData = result.data;
                // 分页
                layui.use(['laypage', 'layer'], function () {
                    var laypage = layui.laypage;
                    laypage({
                        cont: 'turn_page',
                        curr: result.data.current || 1,
                        pages: result.data.pages,
                        skin: '#457fe6',
                        skip: true,
                        jump: function (obj, first) {
                            if (!first) {
                                self.filterParameters.current = obj.curr;
                                self.renderMain(url,self.filterParameters);
                            }
                        }
                    });
                })
            },{
                type:'post',
                noFilter: false  //过滤掉 {}, '', -1 这三种值
            })
        },
        //渲染跟进记录数据
        renderFollowRecords:function(url,param){
            var self = this;
            param = param == undefined ? {} : param;
            console.log(param)
            Customer.axiosRequest(url,param,function(result){
                self.followRecord = result.data;
                // 分页
                layui.use(['laypage', 'layer'], function () {
                    var laypage = layui.laypage;
                    laypage({
                        cont: 'turn_page_follow',
                        curr: result.data.current || 1,
                        pages: result.data.pages,
                        skin: '#457fe6',
                        skip: true,
                        jump: function (obj, first) {
                            if (!first) {
                                self.followPage.filterParameters.current = obj.curr;
                                self.renderFollowRecords(url,self.followPage.filterParameters);
                            }
                        }
                    });
                })
            },{
                type:'post',
                noFilter: false  //过滤掉 {}, '', -1 这三种值
            })
        },
        //渲染证书证照记录数据
        renderCertificateRecords:function(url,id){
            var self = this;
            Customer.axiosRequest(url,{
                custId: id
            },function(result){
                self.certificateRecord.records = result.data;
            },{
                type:'post',
                noFilter: false  //过滤掉 {}, '', -1 这三种值
            })
        },
        //渲染意向记录数据
        renderIntentionRecords:function(url,param){
            var self = this;
            param = param == undefined ? {} : param;
            console.log(param)
            Customer.axiosRequest(url,param,function(result){
                self.intentionRecord = result.data;
                // 分页
                layui.use(['laypage', 'layer'], function () {
                    var laypage = layui.laypage;
                    laypage({
                        cont: 'turn_page_intention',
                        curr: result.data.current || 1,
                        pages: result.data.pages,
                        skin: '#457fe6',
                        skip: true,
                        jump: function (obj, first) {
                            if (!first) {
                                self.intentionPage.filterParameters.current = obj.curr;
                                self.renderIntentionRecords(url,self.intentionPage.filterParameters);
                            }
                        }
                    });
                })
            },{
                type:'post',
                noFilter: false  //过滤掉 {}, '', -1 这三种值
            })
        },
        //渲染商标案件记录数据（GET请求）
        renderCaseRecords:function(url,param){
            var self = this;
            param = param == undefined ? {} : param;
            console.log(param)
            axios.get(url,{
                params:param
            }).then(function(response){
                var data = response.data;
                if(data.code == 0){
                    self.caseRecord = data.data;
                    // 分页
                    layui.use(['laypage', 'layer'], function () {
                        var laypage = layui.laypage;
                        laypage({
                            cont: 'turn_page_case',
                            curr: data.data.current || 1,
                            pages: data.data.pages,
                            skin: '#457fe6',
                            skip: true,
                            jump: function (obj, first) {
                                if (!first) {
                                    self.casePage.filterParameters.current = obj.curr;
                                    self.renderCaseRecords(url,self.casePage.filterParameters);
                                }
                            }
                        });
                    })
                }
            })
            /*Customer.axiosRequest(url,param,function(result){
                self.caseRecord = result.data;
                // 分页
                layui.use(['laypage', 'layer'], function () {
                    var laypage = layui.laypage;
                    laypage({
                        cont: 'turn_page_case',
                        curr: result.data.current || 1,
                        pages: result.data.pages,
                        skin: '#457fe6',
                        skip: true,
                        jump: function (obj, first) {
                            if (!first) {
                                self.casePage.filterParameters.current = obj.curr;
                                self.renderCaseRecords(url,self.casePage.filterParameters);
                            }
                        }
                    });
                })
            },{
                type:'post',
                noFilter: false  //过滤掉 {}, '', -1 这三种值
            })*/
        },
        //清除关键词搜索内容
        removeSearchKey:function(){
            this.filterParameters.searchKey = ''
        },
        //查询
        query:function(){
            var self = this;
            var url = Customer.interface.queryPage;
            var obj = VUE_UTIL.getCode(self.$refs.location);
            //更新code数据
            if(!VUE_UTIL.isObjectEmpty(obj)){
                this.filterParameters.provinceCode = obj.provinceCode == undefined ? -1 : obj.provinceCode;
                this.filterParameters.cityCode = obj.cityCode == undefined ? -1 : obj.cityCode;
                this.filterParameters.countyCode = obj.countyCode == undefined ? -1 : obj.countyCode;
            }else{
                this.filterParameters.provinceCode = '';
                this.filterParameters.cityCode = '';
                this.filterParameters.countyCode = '';
            }
            //搜索结果默认第一页
            this.filterParameters.current = 1;
            this.renderMain(url,self.filterParameters);
        },
        //获取当前用户名信息
        gainCurrentUserInfo:function(){
            var self = this;
            axios.get(Customer.interface.accountDetail).then(function(response){
                var data = response.data;
                if(data.code == 0){
                    self.userInfo = data.data;
                }
            })
        },
        //显示员工弹窗并赋值
        showEmployeeModal:function(){
            var self = this;
            self.modal.employee = true;
            self.$store.state.selectedEmployees = self.finalSelectedEmployees.slice(0);//深拷贝
        },
        //加载部门树形结构
        renderDepartData:function(){
            var self = this;
            var url = Customer.interface.departTree;
            Customer.axiosRequest(url,{},function(result){
                self.departTree.originalData = result.data;
                self.departTree.msg = self.transFormatToTree(self.departTree.originalData);
            },{
                type:'post'
            })
        },
        //转换为树形数据结构
        transFormatToTree:function(data){
            var obj = {};
            for(var i = 0;i<data.length;i++){
                var key = data[i]['id'];
                obj[key] = {
                    'Name': data[i]['name'].toString(),
                    'ID': data[i]['id'].toString(),
                    'ParentID': data[i]['parentId'].toString()
                }
            }
            var resultObj = convert(obj,0) //根id为0
            function convert(source,rootpid){
                var tmp={},parent,n;
                for(n in source){
                    var item=source[n];
                    if(item.ID==item.ParentID){
                        parent=item.ID;
                    }
                    if(!tmp[item.ID]){
                        tmp[item.ID]={};
                    }
                    tmp[item.ID].name=item.Name;
                    tmp[item.ID].id=item.ID;
                    if(!("children" in tmp[item.ID]))tmp[item.ID].children=[];

                    if(item.ID!=item.ParentID){
                        if(tmp[item.ParentID]){
                            tmp[item.ParentID].children.push(tmp[item.ID]);
                        }
                        else{
                            tmp[item.ParentID]={children:[tmp[item.ID]]};
                        }
                    }
                }
                return tmp[rootpid];
            }
            return resultObj.children
        },
        //（选择员工）
        selectEmployeeData:function(id,name){
            var transParam = {
                id: id,
                name: name
            }
            store.commit('updateEmployees',transParam)
        },
        //（选择员工）删除员工
        deleteEmployee:function(id,name){
            var transParam = {
                id: id,
                name: name
            }
            store.commit('deleteEmployee',transParam)
        },
        // （选择员工）确定员工
        confirmEmployees:function(){
            var self = this;
            self.modal.employee = false;
            self.finalSelectedEmployees  = self.$store.state.selectedEmployees.slice(0);//深拷贝
        },
        //查企业信息跳转
        queryEnterpriseInfo:function(id){
            debugger
            var self = this;
            //客户详情获取企业id
            Customer.axiosRequest(Customer.interface.signDetail,{id:id},function(result){
                if(result.code == 0){
                    var custQueryId = result.data.custQueryId;
                    //把查询到的公司ID储存到浏览器本地，跳转的页面通过本地储存来获取ID
                    window.localStorage.setItem('companyId',custQueryId)
                    console.info('companyId',custQueryId);
                    //请求成功以后跳转页面
                    //新加的TAB ID必须从1000起步
                    //1.请求ID
                    //2.tab显示的名称
                    //3.请求的地址
                    window.parent.erpWrap.insertTab(1000, "企业详情", "/enterprise/details");
                }
            },{
                type:'post'
            });
        },
        //跟进
        showFollowModal:function(obj){
            var self = this;
            //清空员工表
            store.commit('deleteEmployee',{
                clearAll: true
            })
            //默认为当前时间
            var followTime = document.getElementById('followTime');
            var currentTime = new Date().getTime();
            followTime.value = Customer.dateFormat(currentTime);
            // self.followInfo.followTime = new Date().getTime();
            //跟进人获取当前登录名
            self.finalSelectedEmployees = [];
            self.finalSelectedEmployees.push({
                id: self.userInfo.employId,
                name: self.userInfo.employName
            });
            self.followInfo.custId = obj.id;
            self.followInfo.customerName = obj.companyName;
            self.followInfo.contactId = obj.contactId;

            //最终员工选择变化
            store.commit('updateEmployees',{
                id: self.userInfo.employId,
                name: self.userInfo.employName
            })
            //联系人选择
            self.followInfo.selectedContactNames = obj.contactName;
            self.updateContacts(obj.id);
            //暂存当前客户信息
            self.custItemStorage = obj;
            //数据词典归零
            self.followInfo.followReasonId = -1;
            self.followInfo.followType = -1;
            $('#followupWay').dropdown('clear');
            $('#followupReason').dropdown('clear');
            //客户对接人置空
            self.followInfo.selectedContactInfo = [];
            //跟进详情清空
            self.followInfo.followDetail=''
            self.$nextTick(function(){
                //重新调一次时间组件
                wzERP.Common.singleDate('.single-date');
            })

            //（获取数据词典）跟进方式
            var followupWayUrl = Customer.interface.dictList + '?code=' + Customer.dictCode[2];
            Customer.axiosRequest(followupWayUrl,{},function(result){
                if(result.code == 0){
                    self.dictData.followupWay = result.data;
                }
            })
            //（获取数据词典）跟进事由
            var followupReasonUrl = Customer.interface.dictList + '?code=' + Customer.dictCode[3];
            Customer.axiosRequest(followupReasonUrl,{},function(result){
                if(result.code == 0){
                    self.dictData.followupReason = result.data;
                }
            })
            //
            self.modal.followRecord = true;
        },
        //客户对接人选择联系人
        upposition:function(item,index){
            var self = this;
            if(typeof index == 'number'){
                self.queryContacts.result.splice(index,1);
            }
            self.followInfo.selectedContactInfo.push({
                id: item.id,
                contactName: item.contactName,
                contactNumber: item.contactNumber
            });
        },
        //删掉已选择的联系人
        downposition:function(item,index){
            var self = this;
            if(typeof index == 'number'){
                self.followInfo.selectedContactInfo.splice(index,1);
            }
            self.queryContacts.result.push({
                id: item.id,
                contactName: item.contactName,
                contactNumber: item.contactNumber
            });
        },
        //显示添加联系人弹窗
        showContactModal:function(){
            var self = this;
            self.modal.contact = true;
            self.clearAllfields(self.req.addContact); //置空字段
            //dropdown clear
            $('#validateModalContact .dropdown').dropdown('clear');
        },
        //添加联系人弹窗保存
        saveContact:function(){
            var self = this;

            //联系人验证
            if(!!Customer.checkform('#validateModalContact')){
                return false;
            }


            var id = self.custItemStorage.id;
            var birthday = $('#modal_contact_birthday').val();
            Vue.set(self.req.addContact,'custId',id);
            Vue.set(self.req.addContact,'birthday',birthday);
            axios.post(Customer.interface.addOrUpdateContact,self.req.addContact).then(function(response){
                var data = response.data;
                if(data.code == 0){
                    layer.msg('添加成功',{time:1000});
                    // self.updateContacts(id);
                    self.upposition({
                        id: data.data.id,
                        contactName: self.req.addContact.contactName,
                        contactNumber: self.req.addContact.phoneNumber
                    })
                }else{
                    layer.msg(data.code,{time:1000})
                }
                self.modal.contact = false;
            })
        },
        //更新联系人
        updateContacts:function(id){
            var self = this;
            //获取当前客户联系人系列
            Customer.axiosRequest(Customer.interface.contactInfo,{
                custId: id,
                types: 1 //0：意向，1:签约 2 潜在
            },function(result){
                if(result.code == 0){
                    self.queryContacts.result = result.data
                }
            },{
                type:'post'
            });
        },
        //添加跟进记录
        addFollowRecords:function(){
            /**
             * 请求配置项
             */
            var self=this;
            var url = Customer.interface.addOrUpdateFollowRecords;

            //时间处理
            var followTime = $('#followTime').val();
            self.followInfo.followTime = followTime;
            //获取跟进人id集合
            self.followInfo.followIds = [];
            for(var i =0; i<self.$store.state.selectedEmployees.length;i++){
                var item = self.$store.state.selectedEmployees[i]
                self.followInfo.followIds.push(item['id'])
            }
            //获取对接人id集合
            self.followInfo.custConcats = [];
            for(var i =0; i<self.followInfo.selectedContactInfo.length;i++){
                var item = self.followInfo.selectedContactInfo[i]
                self.followInfo.custConcats.push(item['id'])
            }

            //验证-S
            var validateObj = self.followInfo;
            var validateParam = {
                'followIds': {
                    msg: '请选择跟进人',
                },
                'followTime': {
                    msg: '请输入跟进时间',
                },
                'followType': {
                    msg: '请选择跟进方式',
                },
                'followReasonId': {
                    msg: '请选择跟进事由',
                },
                'custConcats': {
                    msg: '请选择客户对接人',
                },
                'followDetail': {
                    msg: '请填写跟进详情',
                },
            };
            if(!Customer.validate(validateObj,validateParam)){
                return false;
            }
            //验证-E


            //去掉-1,{},''
            var param = {};
            var originObj = self.followInfo;
            for(var index in originObj) {
                if (originObj.hasOwnProperty(index)) {
                    if (JSON.stringify(originObj[index]) !== '{}' && originObj[index] !== '' && originObj[index] !== -1 && originObj[index] != null  ) {
                        param[index] = originObj[index]
                    }
                }
            }
            // selectedContactInfo
            //提交跟进记录数据
            axios.post(url, param).then(function (response) {
                var data = response.data;
                if(data.code == 0){
                    self.modal.followRecord = false
                    layer.msg('添加成功！',{time:1000})
                    //渲染
                    self.renderFollowRecords(Customer.interface.followRecords,self.followPage.filterParameters)
                }else{
                    layer.msg(data.msg,{time:1000})
                }
            })
        },
        //弹窗清空
        clearAllfields:function(obj){
            var self = this;
            for(var i in obj){
                if(obj.hasOwnProperty(i)){
                    //特殊场景
                    if(i == 'gender' || i == 'gongLiFlag'){obj[i] = 0; continue}
                    if(i == 'intentionType' || i == 'types' || i == 'contactType'){continue}
                    //
                    var type = Object.prototype.toString.call(obj[i]).slice(8,-1);
                    switch(type){
                        case 'Array':
                            obj[i] = []
                            break
                        case 'String':
                            obj[i] = ''
                            break
                        case 'Number':
                            obj[i] = obj[i] === -1 ? -1: 0
                            break
                    }
                }
            }
        },
        //编辑+详情
        handleContent:function(item,handleType){
            /**
             * @handleType    0: 详情   1:编辑
             */
            var self = this;
            self.sLoading = true; //loading
            self.handle.state = handleType;
            self.handle.display = true; //显示操作页面
            // self.custItemStorage = item; //暂存客户资料 注：（这里返回是id不是custId）
            //客户详情获取企业id
            Customer.axiosRequest(Customer.interface.signDetail,{id:item.id},function(result){
                if(result.code == 0){
                    var data = result.data;
                    self.custItemStorage = data;
                    //
                    self.handle.data.basicContent.id = data.id; //客户id
                    self.handle.data.basicContent.companyName = data.customerName; //公司名称
                    self.handle.data.basicContent.logoUrl = data.logoUrl; //企业logo
                    self.handle.data.basicContent.contactNumber = data.contactNumber; //联系电话
                    self.handle.data.basicContent.fax = data.fax; //联系传真
                    self.handle.data.basicContent.emailAddress = data.emailAddress; //邮箱地址
                    self.handle.data.basicContent.corporateLink = data.corporateLink; //企业官网
                    self.handle.data.basicContent.registAddr = data.registAddr; //公司注册地址
                    self.handle.data.basicContent.creditCode = data.creditCode; //统一社会信用代码
                    self.handle.data.basicContent.registrationNumber = data.registrationNumber; //注册号
                    self.handle.data.basicContent.industryCode = data.industryCode; //所属行业
                    self.handle.data.basicContent.industrySearchContent = data.industryCode; //所属行业
                    self.handle.data.basicContent.enterpriseLegalPerson = data.enterpriseLegalPerson; //公司类型
                    self.handle.data.basicContent.registeredCapital = data.registeredCapital; //注册资本
                    self.handle.data.basicContent.taxRegistrationCertificate = data.taxRegistrationCertificate; //税务登记证
                    self.handle.data.basicContent.provinceCode = data.provinceCode; //省编码
                    self.handle.data.basicContent.cityCode = data.cityCode; //市编码
                    self.handle.data.basicContent.countyCode = data.countyCode; //区编码
                    self.handle.data.basicContent.citypickerAddress = data.provinceName + '/' + data.cityName + '/' + data.countyName; //后台返回省市区地址
                    self.handle.data.basicContent.detailAddr = data.detailAddr; //联系详细地址
                    self.handle.data.basicContent.englishName = data.englishName; //英文名称
                    self.handle.data.basicContent.englishAddr = data.englishAddr; //英文地址
                    self.handle.data.basicContent.organizationCode = data.organizationCode; //组织机构代码证
                    self.handle.data.basicContent.enterpriseNatureCodeId = data.enterpriseNatureCodeId == 0 ? -1 : data.enterpriseNatureCodeId; //公司类型
                    self.handle.data.basicContent.enterpriseNatureCode = data.enterpriseNatureCode; //公司类型
                    self.handle.data.basicContent.enterpriseStatusCodeId = data.enterpriseStatusCodeId == 0 ? -1 : data.enterpriseStatusCodeId; //经营状态
                    self.handle.data.basicContent.enterpriseStatusCode = data.enterpriseStatusCode; //经营状态
                    self.handle.data.basicContent.custIntentionDetail = data.custIntentionDetail; //客户意向
                    self.handle.data.basicContent.establishDate = data.establishDate; //成立日期
                    self.handle.data.basicContent.doBusinessStart = data.doBusinessStart; //营业期限（开始时间）
                    self.handle.data.basicContent.doBusinessEnd = data.doBusinessEnd; //营业期限（结束时间）
                    self.handle.data.basicContent.approvalDate = data.approvalDate; //发照日期
                    self.handle.data.basicContent.registAuthority = data.registAuthority; //登记机关
                    self.handle.data.basicContent.custPostCode = data.custPostCode; //邮编
                    self.handle.data.basicContent.scopeBusiness = data.scopeBusiness; //经营范围

                    //获取当前客户联系人
                    Customer.axiosRequest(Customer.interface.contactInfo,{
                        custId: self.custItemStorage.id,
                        types: 1 //0：意向，1:签约 2 潜在
                    },function(result){
                        if(result.code == 0){
                            self.contactsData = result.data;
                        }
                    },{
                        type:'post'
                    });
                    //获取当前客户发票抬头
                    Customer.axiosRequest(Customer.interface.invoiceInfo,{
                        custId: self.custItemStorage.id,
                    },function(result){
                        if(result.code == 0){
                            self.invoicesData = result.data;
                        }
                    },{
                        type:'post'
                    });

                    //
                    self.$nextTick(function(){
                        $('.ui.checkbox').checkbox();
                        $('#edit_city2').citypicker();
                        Customer.verifier('.file-verifier');
                        //时间控件
                        wzERP.Common.singleDate('.single-date');
                        wzERP.Common.inlineDate('.rangestart','.rangeend')
                        //remove loading
                        setTimeout(function(){
                            self.sLoading = false;
                        },100)
                    })

                    //证书证照渲染
                    self.renderCertificateRecords(Customer.interface.certificateRecords,item.id);

                    //跟进记录渲染
                    self.followPage.filterParameters.id = item.id;
                    self.renderFollowRecords(Customer.interface.followRecords,self.followPage.filterParameters);

                    if(handleType == 0){
                        //意向记录渲染
                        self.intentionPage.filterParameters.id = item.id;
                        self.renderIntentionRecords(Customer.interface.intentionRecords,self.intentionPage.filterParameters);
                        //商标案件记录渲染
                        self.casePage.filterParameters.custId = item.id;
                        self.renderCaseRecords(Customer.interface.caseRecords,self.casePage.filterParameters);
                    }

                }else{
                    layer.msg(result.msg,{time:1000})
                }
            },{
                type:'post'
            });


            //（获取数据词典）公司类型
            var entrepreneurialUrl = Customer.interface.dictList + '?code=' + Customer.dictCode[4];
            Customer.axiosRequest(entrepreneurialUrl,{},function(result){
                if(result.code == 0){
                    self.dictData.entrepreneurial = result.data;
                }
            })
            //（获取数据词典）经营状况
            var enterpriseAppearanceUrl = Customer.interface.dictList + '?code=' + Customer.dictCode[5];
            Customer.axiosRequest(enterpriseAppearanceUrl,{},function(result){
                if(result.code == 0){
                    self.dictData.enterpriseAppearance = result.data;
                }
            })
            //（获取数据词典）证照类型
            var licenseTypeUrl = Customer.interface.dictList + '?code=' + Customer.dictCode[1];
            Customer.axiosRequest(licenseTypeUrl,{},function(result){
                if(result.code == 0){
                    self.dictData.licenseType = result.data;
                }
            })


        },
        //监听所属行业搜索内容变化
        industrySearchChange:function(val){
            var self = this;
            self.handle.industrySearchResult.hasResult = false;//先设无
            if(val == ''){
                self.handle.industrySearchResult.display = false
            }else{
                Customer.axiosRequest(Customer.interface.findIndustryBySearch,{
                    searchKey: val
                },function(result){
                    self.handle.industrySearchResult.display = true
                    if(result.code == 0){
                        if(result.data.length == 0){
                            //无返回结果时
                            self.handle.industrySearchResult.hasResult = false;
                            self.handle.industrySearchResult.content = [{
                                industryName: '无返回结果!'
                            }];
                        }else{
                            self.handle.industrySearchResult.hasResult = true;
                            self.handle.industrySearchResult.content = result.data;
                        }
                    }else{
                        self.handle.industrySearchResult.hasResult = false;
                        self.handle.industrySearchResult.content = [{
                            industryName: '网络错误!'
                        }];
                    }
                },{
                    type:'post',
                })
            }
        },
        //确认所属行业id
        confirmIndustryCodeId:function(item){
            var self = this;
            self.handle.data.basicContent.industryCodeId = item.id;
            if(!!self.handle.industrySearchResult.hasResult){
                self.handle.data.basicContent.industrySearchContent = item.industryName;
            }
            self.handle.industrySearchResult.display = false;
        },
        //所属行业blur
        blurDealResults:function(){
            var self = this;
            if(!self.handle.industrySearchResult.hasResult){
                self.handle.industrySearchResult.display = false;
            }
        },
        //切换
        toggleDisplay:function(vObj){
            var display = vObj.display;
            Vue.set(vObj,'display',!display);
        },
        //业务限制人数
        limitedNum:function(selectedNum,id){
            /*Arg Guide
             @ selectedNum 已选择的人数
             @ id 点击的员工id
             */
            var self = this;
            var followLimited = 5; //跟进记录限制5个人
            var assignLimited = 3; //指派限制3个人

            var selectedEmployees = self.selectedEmployees;

            if(self.modal.followRecord == true && selectedEmployees.indexOf(id) == -1 && selectedNum >= followLimited ){
                layer.msg('限制'+followLimited+'个人',{time:1000})
                return false
            }else if(self.modal.assign == true && selectedEmployees.indexOf(id) == -1 && selectedNum >= assignLimited ){
                layer.msg('限制'+assignLimited+'个人',{time:1000})
                return false
            }else{
                return true
            }
        },
        //打开证照弹窗
        openCerticateModal:function(){
            var self = this;
            self.modal.certificate = true;
            //清空
            self.req.addCerticate.docType = -1;
            Customer.clearPdf('uploadCertificate1_label');//清除pdf
        },
        //添加证照
        addCerticate:function(){
            var self = this;
            //字段处理
            self.req.addCerticate.custId = self.custItemStorage.id; //客户id
            self.req.addCerticate.pdfUrl =  $('#cert_pdf_url').val();
            //验证
            if(self.req.addCerticate.docType == -1){
                layer.msg('请选择证照类型！',{time:1000})
                return false
            }else if(self.req.addCerticate.pdfUrl == ''){
                layer.msg('请上传证照！',{time:1000})
                return false
            }else{}

            console.log(self.req.addCerticate)
            if(!self.fastClick.certificate){
                self.fastClick.certificate = true;
                //
                axios.get(Customer.interface.addOrUpdateCertificate, {
                    params:self.req.addCerticate
                }).then(function (response) {
                    var data = response.data;
                    if(data.code == 0){
                        layer.msg('添加成功',{time:1000});
                        self.modal.certificate = false;
                        //渲染
                        self.renderCertificateRecords(Customer.interface.certificateRecords,self.custItemStorage.id)
                    }else{
                        layer.msg(data.msg,{time:1000})
                    }
                    self.fastClick.certificate = false;
                })
            }

        },
        //渲染证书证照数据
        renderCertificate:function(url,param){
            var self = this;
            param = param == undefined ? {} : param;
            Customer.axiosRequest(url,param,function(result){
                self.formData = result.data;
            },{
                type:'post',
                noFilter: false  //过滤掉 {}, '', -1 这三种值
            })
        },
        //提交签约客户基本信息
        submissionSign:function(){
            var self = this;
            //验证-S
            if(!!Customer.checkform('#whole_ibox >.file-verifier') || !!Customer.checkform('#whole_ibox .ui.tab.active .file-verifier') ){
                //location判断
                Customer.checkLocation('#whole_ibox');
                /*--------错误提示和位置处理------S------*/
                var firstError = $('#whole_ibox').find('.ui.field.error').eq(0);//获取第一个错误
                var firstErrorMsg = firstError.find('.ui.basic.red.label').text();
                if (firstErrorMsg == '' && firstError.find('.city-picker-span').length
                    > 0) {
                    firstErrorMsg = '请至少选择省市区域!'
                }
                //获取第一个报error相对顶部的距离
                var curActive = $('#whole_ibox');
                var topToWindow = firstError.offset().top;
                /*var scrollBoxToWindow = curActive.offset().top;
                var scrollLength = curActive.scrollTop();
                var verticalShift = topToWindow + scrollLength - scrollBoxToWindow;*/
                //滚动到error的位置
                curActive.scrollTop(topToWindow - 8);
                //获取error提示信息
                layer.msg(firstErrorMsg, {time: 1000});
                /*--------错误提示和位置处理------E------*/
                return false;
            }
            //验证-E

            //字段处理
            self.handle.data.basicContent.logoUrl = $('#logo_url').val(); //logo url
            self.handle.data.basicContent.registeredCapital = $('#registered_capital').val() * Math.pow(10,6); //注册资本
            self.handle.data.basicContent.establishDate = $('#createDate').val(); //成立日期
            self.handle.data.basicContent.doBusinessStart = $('#startDate').val(); //营业期限成立日期
            self.handle.data.basicContent.doBusinessEnd = $('#endDate').val(); //营业期限结束日期
            self.handle.data.basicContent.approvalDate = $('#approvedDate').val(); //发照日期
            self.handle.data.basicContent.provinceCode = $('#edit_city2').data('citypicker').getCode('province'); //获取省编码
            self.handle.data.basicContent.cityCode = $('#edit_city2').data('citypicker').getCode('city'); //获取市编码
            self.handle.data.basicContent.countyCode = $('#edit_city2').data('citypicker').getCode('district') == undefined ? '' : $('#edit_city2').data('citypicker').getCode('district'); //获取区编码

            //去掉-1,{}
            var param = {};
            var originObj = self.handle.data.basicContent;
            for(var index in originObj) {
                if (originObj.hasOwnProperty(index)) {
                    if (JSON.stringify(originObj[index]) !== '{}' && originObj[index] !== -1 && originObj[index] != null  ) {
                        param[index] = originObj[index]
                    }
                }
            }
            //提交客户数据
            Customer.axiosRequest(Customer.interface.addOrUpdateCustomer,param,function(result){
                if(result.code == 0){
                    layer.msg('保存成功',{time:1000})
                }else{
                    layer.msg(result.msg,{time:1000})
                }
            },{
                type:'post',
                noFilter: true  //
            })
        },
        //跳转到意向详情
        queryIntentionInfo:function(id){
            //id 意向id
            //把查询到的公司ID储存到浏览器本地，跳转的页面通过本地储存来获取ID
            window.localStorage.setItem('intentionId',id);
            console.info('intentionId',id);
            //请求成功以后跳转页面
            //新加的TAB ID必须从1000起步
            //1.请求ID
            //2.tab显示的名称
            //3.请求的地址
            window.parent.erpWrap.insertTab(214, "意向客户", "/customer/queryPage");
        },
        //跳转到案件详情
        caseContent:function(id){
            VUE_UTIL.setLocalStorage('caseId',id)
            console.info('companyId',id);
            //请求成功以后跳转页面
            window.parent.erpWrap.insertTab(201, "商标案件", "/trademark/case/queryByPageHtml");
        },
        //返回主页
        returnToMain:function(){
            var self = this;
            self.handle.display = false;
        },
    }
})